package com.iotechn.unimall.app.api.running;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iotechn.unimall.core.exception.AppServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.RunningAdminApplyDO;
import com.iotechn.unimall.data.domain.RunningGroupUserDO;
import com.iotechn.unimall.data.domain.UserDO;
import com.iotechn.unimall.data.dto.RunningAdminApplyDTO;
import com.iotechn.unimall.data.enums.RunningStatus;
import com.iotechn.unimall.data.enums.UserLevelType;
import com.iotechn.unimall.data.mapper.RunningAdminApplyMapper;
import com.iotechn.unimall.data.mapper.RunningGroupUserMapper;
import com.iotechn.unimall.data.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by rize on 2019/6/30.
 */
@Service
public class RunningAdminApplyServiceImpl implements RunningAdminApplyService {


    private static final Logger logger = LoggerFactory.getLogger(RunningAdminApplyServiceImpl.class);

    @Autowired
    private RunningAdminApplyMapper runningAdminApplyMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RunningGroupUserMapper runningGroupUserMapper;


    private static String CHINESE_DATE_FORMAT= "yyyy年MM月dd日 HH点mm分";


    @Override
    public Page<RunningAdminApplyDTO> selectApplyPage(Long userId, Integer pageNo, Integer pageSize) {
        Long runningGroupId = -1L;
        UserDO userDO = userMapper.selectById(userId);
        if(userDO!=null){
            runningGroupId = userDO.getRunningGroupId();
        }
        Page<RunningAdminApplyDTO> page=new Page(pageNo,pageSize);
        List<RunningAdminApplyDTO> list = runningAdminApplyMapper.selectApplyPage(page,runningGroupId);
        for(RunningAdminApplyDTO dto:list){
            String format = DateUtil.format(dto.getGmtCreate(), CHINESE_DATE_FORMAT);
            dto.setGmtCreateStr(format);
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public Boolean apply(Long userId) throws ServiceException {
        Long runningGroupId = -1L;

        UserDO userDO = userMapper.selectById(userId);
        if(userDO!=null){
//            if(userDO.getLevel()<1||userDO.getRunningGroupId()==null){
//                throw new AppServiceException(ExceptionDefinition.RUNNING_GROUP);
//            }
//
//            if(userDO.getLevel()>1){
//                throw new AppServiceException(ExceptionDefinition.RUNNING_ADMIN_APPLY);
//            }

            runningGroupId = userDO.getRunningGroupId();
            if(runningGroupId==null){
                throw new AppServiceException(ExceptionDefinition.RUNNING_GROUP);
            }
        }

        RunningGroupUserDO runningGroupUserDO = runningGroupUserMapper.selectByGroupIdAndUserId(runningGroupId, userId);
        if(runningGroupUserDO!=null){
            if(runningGroupUserDO.getLevel()<1||runningGroupUserDO.getRunningGroupId()==null){
                throw new AppServiceException(ExceptionDefinition.RUNNING_GROUP);
            }

            if(runningGroupUserDO.getLevel()>1){
                throw new AppServiceException(ExceptionDefinition.RUNNING_ADMIN_APPLY);
            }
        }


        Integer recordNum = runningAdminApplyMapper.selectCount(new QueryWrapper<RunningAdminApplyDO>()
                .eq("user_id", userId)
                .eq("running_group_id",runningGroupId)
                .eq("status", RunningStatus.NO_CHECK.getCode()));
        if(recordNum>0){
            throw new AppServiceException("管理员申请已发出，请等候批准", 200);
        }

        RunningAdminApplyDO runningAdminApplyDO=new RunningAdminApplyDO();
        runningAdminApplyDO.setUserId(userId);
        runningAdminApplyDO.setStatus(RunningStatus.NO_CHECK.getCode());
        runningAdminApplyDO.setGmtCreate(new Date());
        runningAdminApplyDO.setGmtUpdate(new Date());
        runningAdminApplyDO.setRunningGroupId(runningGroupId);
        runningAdminApplyMapper.insert(runningAdminApplyDO);
        throw new AppServiceException("管理员申请已发出，请等候批准", 200);
    }

    @Override
    public Boolean approvalRecord(Long recordId, Integer status, Long userId) throws ServiceException {
        RunningAdminApplyDO runningAdminApplyDO=new RunningAdminApplyDO();
        runningAdminApplyDO.setId(recordId);
        runningAdminApplyDO.setCheckUserId(userId);
        runningAdminApplyDO.setStatus(status);
        runningAdminApplyDO.setGmtUpdate(new Date());

        Integer update = runningAdminApplyMapper.update(runningAdminApplyDO //更新数据
                , new QueryWrapper<RunningAdminApplyDO>()
                        .eq("id", recordId)
                        .eq("status", RunningStatus.NO_CHECK.getCode())
        );
        //审核通过，修改用户所在跑团的等级
        if(status.equals(RunningStatus.PASS.getCode())&&update>0){
            RunningAdminApplyDO adminApplyDO = runningAdminApplyMapper.selectById(recordId);
            if(adminApplyDO!=null){
//                UserDO userUpdateDO = new UserDO();
//                userUpdateDO.setId(adminApplyDO.getUserId());
//                userUpdateDO.setLevel(UserLevelType.SUPER_VIP.getCode());
//                userUpdateDO.setGmtUpdate(new Date());
//                userMapper.updateById(userUpdateDO);

                RunningGroupUserDO runningGroupUserDO = runningGroupUserMapper.selectByGroupIdAndUserId(adminApplyDO.getRunningGroupId(), adminApplyDO.getUserId());
                if(runningGroupUserDO!=null){
                    RunningGroupUserDO updateGroupUser = new RunningGroupUserDO();
                    updateGroupUser.setId(runningGroupUserDO.getId());
                    updateGroupUser.setLevel(UserLevelType.SUPER_VIP.getCode());
                    updateGroupUser.setGmtUpdate(new Date());
                    runningGroupUserMapper.updateById(updateGroupUser);
                }

            }
        }
        return true;
    }


}
